#include <stdio.h>
#include <pthread.h>
#include <stdlib.h>
#include <unistd.h>

pthread_mutex_t mutex;
int g_data = 0;

void *func1(void* arg){

//int pthread_mutex_lock(pthread_mutex_t *mutex);
	pthread_mutex_lock(&mutex);
	printf("t1:%ld\n",(unsigned long)pthread_self());
	printf("t1:param is %d\n",*(int*)arg);
	while(1){
		sleep(1);
		g_data++;
		printf("t1:g_data = %d\n",g_data);
		if(g_data == 5){
			printf("t1 done!!\n");
			pthread_mutex_unlock(&mutex);
			break;
		}
	}
}


void *func2(void* arg){

	sleep(1);
	static int ret = 666;
	pthread_mutex_lock(&mutex);

	printf("t2:%ld\n",(unsigned long)pthread_self());
	printf("t2:param is %d\n",*(int*)arg);
	while(1){
		sleep(1);
		g_data++;
		printf("t2:g_data = %d\n",g_data);
		if(g_data == 10){
			printf("t2 done!!\n");
			pthread_exit((void*)&ret);
		}
	}
}

int main(){

//	int pthread_create(pthread_t *thread, const pthread_attr_t *attr,
//                          void *(*start_routine) (void *), void *arg);

	pthread_t t1;
	pthread_t t2;
	int ret;
	int param = 100;
	int *pret;

//	int pthread_mutex_init(pthread_mutex_t *restrict mutex, const pthread_mutexattr_t *restrict attr);
	ret = pthread_mutex_init(&mutex,NULL);
	if(ret == 0){
	
		printf("main: create mutex success\n");
	}
	else{
		
		printf("main: create mutex error\n");
		exit(-1);
	}


	ret = pthread_create(&t1,NULL,&func1,(void*)&param);
	if(ret == 0){
	
		printf("main: create t1 success\n");
	}
	else{
		
		printf("main: create t1 error\n");
		exit(-1);
	}
	ret = pthread_create(&t2,NULL,&func2,(void*)&param);
	if(ret == 0){
	
		printf("main: create t2 success\n");
	}
	else{
		
		printf("main: create t1 error\n");
		exit(-1);
	}

	printf("main: id is %ld\n",(unsigned long)pthread_self());
	//	int pthread_join(pthread_t thread, void **retval);
	pthread_join(t2,(void **)&pret);
	printf("exit pret = %d\n",*pret);
	//int pthread_mutex_destroy(pthread_mutex_t *mutex);
	pthread_mutex_destroy(&mutex);
	return 0;
}

